// 钢网追踪页面

let steelMeshData = [];
let filteredData = [];

// 加载钢网追踪页面
function loadSteelMeshPage(container) {
    container.innerHTML = `
        ${createPageTitle('钢网追踪', 'fas fa-th')}
        ${createToolbar([
            '<button class="btn btn-primary" onclick="showAddSteelMeshModal()">',
            '<i class="fas fa-plus mr-2"></i>新增钢网',
            '</button>',
            '<button class="btn btn-secondary" onclick="loadSteelMeshData()">',
            '<i class="fas fa-refresh mr-2"></i>刷新',
            '</button>',
            '<button class="btn btn-accent" onclick="exportSteelMeshData()">',
            '<i class="fas fa-download mr-2"></i>导出',
            '</button>',
            '<button class="btn btn-warning" onclick="checkOverdueSteelMesh()">',
            '<i class="fas fa-exclamation-triangle mr-2"></i>检查延期',
            '</button>'
        ])}
        <div id="steel-mesh-list">
            ${createSteelMeshTable()}
        </div>
    `;
    
    // 绑定搜索事件
    const searchInput = document.getElementById('search-input');
    if (searchInput) {
        searchInput.addEventListener('input', debounce(handleSteelMeshSearch, 300));
    }
    
    // 加载数据
    loadSteelMeshData();
}

// 创建钢网追踪表格
function createSteelMeshTable() {
    const headers = ['钢网编号', '机型', '工单号', '状态', '开始日期', '预计完成日期', '实际完成日期', '备注', '延期天数'];
    
    return `
        <div class="table-container">
            <table class="table table-zebra w-full">
                <thead>
                    <tr>
                        ${headers.map(header => `<th>${header}</th>`).join('')}
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    ${filteredData.map(item => {
                        const overdueDays = calculateOverdueDays(item.expectedDate, item.actualDate);
                        const statusClass = getStatusClass(item.status, overdueDays);
                        
                        return `
                            <tr class="${overdueDays > 0 ? 'overdue-row' : ''}">
                                <td>${item.meshNumber || '-'}</td>
                                <td>${item.model || '-'}</td>
                                <td>${item.workOrder || '-'}</td>
                                <td><span class="badge ${statusClass}">${item.status || '待处理'}</span></td>
                                <td>${item.startDate || '-'}</td>
                                <td>${item.expectedDate || '-'}</td>
                                <td>${item.actualDate || '-'}</td>
                                <td>${item.remark || '-'}</td>
                                <td>${overdueDays > 0 ? `<span class="text-red-500 font-bold">${overdueDays}天</span>` : '-'}</td>
                                <td>
                                    <div class="btn-group">
                                        <button class="btn btn-sm btn-primary" onclick="editSteelMesh('${item.id}')">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button class="btn btn-sm btn-error" onclick="deleteSteelMesh('${item.id}')">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        `;
                    }).join('')}
                </tbody>
            </table>
        </div>
    `;
}

// 计算延期天数
function calculateOverdueDays(expectedDate, actualDate) {
    if (!expectedDate) return 0;
    
    const today = new Date();
    const expected = new Date(expectedDate);
    
    if (actualDate) {
        const actual = new Date(actualDate);
        return actual > expected ? Math.ceil((actual - expected) / (1000 * 60 * 60 * 24)) : 0;
    } else {
        return today > expected ? Math.ceil((today - expected) / (1000 * 60 * 60 * 24)) : 0;
    }
}

// 获取状态样式类
function getStatusClass(status, overdueDays) {
    if (status === '已完成') return 'badge-success';
    if (status === '进行中') return 'badge-info';
    if (status === '暂停') return 'badge-warning';
    if (overdueDays > 0) return 'badge-error';
    return 'badge-ghost';
}

// 加载钢网数据
async function loadSteelMeshData() {
    try {
        const data = await steelMeshAPI.getAll();
        steelMeshData = data;
        filteredData = data;
        updateSteelMeshTable();
    } catch (error) {
        showError('加载数据失败');
    }
}

// 更新钢网表格
function updateSteelMeshTable() {
    const tableContainer = document.getElementById('steel-mesh-list');
    if (tableContainer) {
        tableContainer.innerHTML = createSteelMeshTable();
    }
}

// 处理搜索
function handleSteelMeshSearch() {
    const query = document.getElementById('search-input')?.value?.trim() || '';
    
    if (!query) {
        filteredData = steelMeshData;
    } else {
        filteredData = steelMeshData.filter(item => 
            item.meshNumber?.toLowerCase().includes(query.toLowerCase()) ||
            item.model?.toLowerCase().includes(query.toLowerCase()) ||
            item.workOrder?.toLowerCase().includes(query.toLowerCase()) ||
            item.remark?.toLowerCase().includes(query.toLowerCase())
        );
    }
    
    updateSteelMeshTable();
}

// 显示新增模态框
function showAddSteelMeshModal() {
    const content = `
        <form id="steel-mesh-form" class="space-y-4">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                ${createFormInput('钢网编号', 'meshNumber', 'text', '', { required: true, placeholder: '请输入钢网编号' })}
                ${createFormInput('机型', 'model', 'text', '', { required: true, placeholder: '请输入机型' })}
                ${createFormInput('工单号', 'workOrder', 'text', '', { required: true, placeholder: '请输入工单号' })}
                ${createFormInput('状态', 'status', 'select', '', { 
                    required: true, 
                    options: [
                        { value: '待处理', text: '待处理' },
                        { value: '进行中', text: '进行中' },
                        { value: '暂停', text: '暂停' },
                        { value: '已完成', text: '已完成' }
                    ]
                })}
                ${createFormInput('开始日期', 'startDate', 'date', '', { required: true })}
                ${createFormInput('预计完成日期', 'expectedDate', 'date', '', { required: true })}
                ${createFormInput('实际完成日期', 'actualDate', 'date', '')}
            </div>
            ${createFormInput('备注', 'remark', 'textarea', '', { placeholder: '请输入备注信息' })}
        </form>
    `;
    
    showModal('新增钢网追踪', content, () => {
        const form = document.getElementById('steel-mesh-form');
        if (form.checkValidity()) {
            const formData = new FormData(form);
            const data = {};
            
            for (let [key, value] of formData.entries()) {
                data[key] = value;
            }
            
            createSteelMesh(data);
        } else {
            form.reportValidity();
        }
    });
    
    // 重新绑定表单提交事件
    setTimeout(() => {
        const modal = document.querySelector('.modal');
        const confirmBtn = modal.querySelector('.btn-primary');
        confirmBtn.onclick = () => {
            const form = document.getElementById('steel-mesh-form');
            if (form.checkValidity()) {
                const formData = new FormData(form);
                const data = {};
                
                for (let [key, value] of formData.entries()) {
                    data[key] = value;
                }
                
                createSteelMesh(data);
                modal.remove();
            } else {
                form.reportValidity();
            }
        };
    }, 100);
}

// 创建钢网追踪
async function createSteelMesh(data) {
    try {
        await steelMeshAPI.create(data);
        showSuccess('创建成功');
        loadSteelMeshData();
    } catch (error) {
        showError('创建失败');
    }
}

// 编辑钢网追踪
function editSteelMesh(id) {
    const item = steelMeshData.find(s => s.id === id);
    if (!item) {
        showError('记录不存在');
        return;
    }
    
    const content = `
        <form id="steel-mesh-edit-form" class="space-y-4">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                ${createFormInput('钢网编号', 'meshNumber', 'text', item.meshNumber, { required: true })}
                ${createFormInput('机型', 'model', 'text', item.model, { required: true })}
                ${createFormInput('工单号', 'workOrder', 'text', item.workOrder, { required: true })}
                ${createFormInput('状态', 'status', 'select', item.status, { 
                    required: true, 
                    options: [
                        { value: '待处理', text: '待处理' },
                        { value: '进行中', text: '进行中' },
                        { value: '暂停', text: '暂停' },
                        { value: '已完成', text: '已完成' }
                    ]
                })}
                ${createFormInput('开始日期', 'startDate', 'date', item.startDate, { required: true })}
                ${createFormInput('预计完成日期', 'expectedDate', 'date', item.expectedDate, { required: true })}
                ${createFormInput('实际完成日期', 'actualDate', 'date', item.actualDate || '')}
            </div>
            ${createFormInput('备注', 'remark', 'textarea', item.remark || '')}
        </form>
    `;
    
    showModal('编辑钢网追踪', content, () => {
        const form = document.getElementById('steel-mesh-edit-form');
        if (form.checkValidity()) {
            const formData = new FormData(form);
            const data = {};
            
            for (let [key, value] of formData.entries()) {
                data[key] = value;
            }
            
            updateSteelMesh(id, data);
        } else {
            form.reportValidity();
        }
    });
    
    // 重新绑定表单提交事件
    setTimeout(() => {
        const modal = document.querySelector('.modal');
        const confirmBtn = modal.querySelector('.btn-primary');
        confirmBtn.onclick = () => {
            const form = document.getElementById('steel-mesh-edit-form');
            if (form.checkValidity()) {
                const formData = new FormData(form);
                const data = {};
                
                for (let [key, value] of formData.entries()) {
                    data[key] = value;
                }
                
                updateSteelMesh(id, data);
                modal.remove();
            } else {
                form.reportValidity();
            }
        };
    }, 100);
}

// 更新钢网追踪
async function updateSteelMesh(id, data) {
    try {
        await steelMeshAPI.update(id, data);
        showSuccess('更新成功');
        loadSteelMeshData();
    } catch (error) {
        showError('更新失败');
    }
}

// 删除钢网追踪
function deleteSteelMesh(id) {
    showConfirmDialog('确定要删除这条记录吗？', async () => {
        try {
            await steelMeshAPI.delete(id);
            showSuccess('删除成功');
            loadSteelMeshData();
        } catch (error) {
            showError('删除失败');
        }
    });
}

// 检查延期钢网
async function checkOverdueSteelMesh() {
    try {
        const overdueItems = await steelMeshAPI.getOverdue();
        
        if (overdueItems.length === 0) {
            showInfo('暂无延期项目');
            return;
        }
        
        // 显示延期提醒
        const content = `
            <div class="space-y-4">
                <p class="text-lg font-semibold text-red-600">发现 ${overdueItems.length} 个延期项目</p>
                <div class="overflow-x-auto">
                    <table class="table table-sm">
                        <thead>
                            <tr>
                                <th>钢网编号</th>
                                <th>机型</th>
                                <th>工单号</th>
                                <th>预计完成日期</th>
                                <th>延期天数</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${overdueItems.map(item => {
                                const overdueDays = calculateOverdueDays(item.expectedDate, item.actualDate);
                                return `
                                    <tr class="text-red-600">
                                        <td>${item.meshNumber}</td>
                                        <td>${item.model}</td>
                                        <td>${item.workOrder}</td>
                                        <td>${item.expectedDate}</td>
                                        <td>${overdueDays}天</td>
                                    </tr>
                                `;
                            }).join('')}
                        </tbody>
                    </table>
                </div>
            </div>
        `;
        
        showModal('延期提醒', content, null, '确定');
        
    } catch (error) {
        showError('检查延期失败');
    }
}

// 导出钢网数据
function exportSteelMeshData() {
    if (filteredData.length === 0) {
        showWarning('没有数据可导出');
        return;
    }
    
    const exportData = filteredData.map(item => ({
        '钢网编号': item.meshNumber,
        '机型': item.model,
        '工单号': item.workOrder,
        '状态': item.status,
        '开始日期': item.startDate,
        '预计完成日期': item.expectedDate,
        '实际完成日期': item.actualDate || '',
        '备注': item.remark || '',
        '延期天数': calculateOverdueDays(item.expectedDate, item.actualDate)
    }));
    
    exportToCSV(exportData, `钢网追踪_${formatDate(new Date(), 'YYYY-MM-DD')}.csv`);
    showSuccess('导出成功');
}

// 绑定到全局作用域
window.loadSteelMeshPage = loadSteelMeshPage;
window.showAddSteelMeshModal = showAddSteelMeshModal;
window.editSteelMesh = editSteelMesh;
window.deleteSteelMesh = deleteSteelMesh;
window.checkOverdueSteelMesh = checkOverdueSteelMesh;
window.exportSteelMeshData = exportSteelMeshData;
